var config = {
  baseApiUrl: 'https://app.i-fdu.com/',
  baseImageUrl: 'http://s.i-fdu.com/runto/images/',
  baseStaticUrl: 'http://s.i-fdu.com/runto/wxa/s/',
};

var showToast = function (obj) {
  if (typeof obj == 'object' && obj.title) {
    if (!obj.duration || typeof obj.duration != 'number') { obj.duration = 1500; }//默认1.5s后消失  
    var that = getCurrentPages()[getCurrentPages().length - 1];//获取当前page实例  
    obj.isShow = true;//开启toast  
    if (obj.duration < 10000) {
      setTimeout(function () {
        obj.isShow = false;
        obj.cb && typeof obj.cb == 'function' && obj.cb();//如果有成功的回调则执行  
        that.setData({
          'showToast.isShow': obj.isShow
        });
      }, obj.duration);
    }
    that.setData({
      showToast: obj
    });
  } else {
    console.log('showToast fail:请确保传入的是对象并且title必填');
  }
}

var hideToast = function () {
  var that = getCurrentPages()[getCurrentPages().length - 1];//获取当前page实例  
  if (that.data.showToast) {
    that.setData({
      'showToast.isShow': false
    });
  }
}

var doRequest = function (url, method, data, success, fail) {
  var fullUrl = config.baseApiUrl + url;
  if (!data['channelId'] || data['channelId'] == 0) {
    data['channelId'] = 21;
  }
  data['rnd'] = Math.random();
  wx.request({
    url: fullUrl,
    method: method,
    data: data,
    success: function (res) {
      console.log(fullUrl, res);

      if (res.data.code != '0000') {
        if (!fail) {
          showToast({
            title: res.data.msg,
            mask: false
          })
          wx.hideLoading();
          return;
        } else {
          fail(res.data);
        }
      }
      success(res.data.data);
    }
  });
}

var api = {
  doRequest: doRequest,
  doGet: function (url, data, success, fail) {
    doRequest(url, 'get', data, success, fail);
  },
  doPost: function (url, data, success, fail) {
    doRequest(url, 'post', data, success, fail);
  }
};

var toast = {
  showToast: showToast,
  hideToast: hideToast
};


module.exports = {
  config: config,
  api: api,
  toast: toast
}